package com.yonyou.wdt.job.config;

import com.yonyou.wdt.dao.JobLogDao;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.job.YsProductToRedisJob;
import com.yonyou.wdt.utils.RateLimiter;
import com.yonyou.wdt.utils.TenantRateLimiter;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName BaseConfig
 * @Description YS与聚水潭租户信息配置信息
 * @Author HuangWb
 * @Date 2023/11/7 16:00
 */
@Data
@Component
public class BaseConfig {

    // YS 配置信息
    @Value("${ys.config.appKey}")
    private String ysAppKey;
    @Value("${ys.config.appSecret}")
    private String ysAppSecret;
    @Value("${ys.config.tenantId}")
    private String ysTenantId;

    private static Logger logger = LoggerFactory.getLogger(BaseConfig.class);
    private TenantRateLimiter tenantRateLimiter = new TenantRateLimiter();

    /**
     * @Author Huangwb
     * @Description 接口限流处理
     * @Date 2024/10/23 15:34
     **/
    public void APICurrentLimiting(String apiUrl, int frequency) {
        boolean isNextFlag;
        do {
            // 尝试调用限流器的call方法
            isNextFlag = tenantRateLimiter.getRateLimiter(ysTenantId, apiUrl, frequency).call();
            if (isNextFlag) {
                logger.info("【{}】接口限流中，频率为：【{}】次/min，等待2.5秒再重试...", apiUrl, frequency);
                // 如果限流，等待一秒再尝试
                try {
                    Thread.sleep(2500); // 每次限流时等待2.5秒
                } catch (InterruptedException e) {
                    logger.error("Thread Sleep Exception", e);
                }
            }
        } while (isNextFlag); // 当限流时继续循环，直到返回false
    }

}
